///
///  CommonHelper.m
///
///
///  Created by mac on 14/12/16.
///  Copyright (c) 2014年 CnbizMedia. All rights reserved.
///

#import "CommonHelper.h"

#import <CommonCrypto/CommonCryptor.h>
#import <CommonCrypto/CommonDigest.h>
@implementation CommonHelper
///getNavigationImageObj
+(NSArray*)getNavigationImageObj:(id)obj{
    UIViewController*view=obj;
    NSMutableArray*array=[[NSMutableArray alloc]init];
    view.navigationController.navigationBar.translucent = NO;
    if ([view.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]){
        NSArray *list=view.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                UIImageView *imageView=(UIImageView *)obj;
                
                NSLog(@"____imageview");
//                imageView.backgroundColor=[UIColor greenColor];
                NSArray *list2=imageView.subviews;
                for (id obj2 in list2) {
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        UIImageView *imageView2=(UIImageView *)obj2;
                        [array addObject:imageView];
                    }
                }
            }
            if ([obj isKindOfClass:[UIView class]]) {
                NSArray *list2=[obj subviews];
                for (id obj2 in list2) {
                if ([obj2 isKindOfClass:[UIButton class]]) {
                    [array addObject:obj2];
                    NSLog(@"____uibutton");
                    }

                }
            }
            if ([obj isKindOfClass:NSClassFromString(@"UINavigationItemView")]) {
                NSArray*a=[obj subviews];
                [array addObject:a[0]];
            }
            
        
            
        }
    }
    return array;
}
///NavigationBar底部的黑线
+(void)NavigationBarHiddenLine:(id)obj{
    
    UIViewController*view=obj;
    view.navigationController.navigationBar.translucent = NO;
    if ([view.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]){
        NSArray *list=view.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                UIImageView *imageView=(UIImageView *)obj;
//                imageView.backgroundColor=[UIColor greenColor];
                NSArray *list2=imageView.subviews;
                for (id obj2 in list2) {
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        UIImageView *imageView2=(UIImageView *)obj2;
//                        imageView2.backgroundColor=[UIColor orangeColor];
//                        imageView2.frame=CGRectMake(imageView2.frame.origin.x, imageView2.frame.origin.y, imageView2.frame.size.width, 50);
                        imageView2.hidden=YES;
                    }
                }
            }
        }
    }
}
///返回缓存根目录地址
+ (NSString *) getCachePath
{
    NSArray *cache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return [cache objectAtIndex:0];
}
#pragma mark - 数据大小不同单位间转换
///将字节转化成M单位，不附带M
+(float)transformToM:(NSString *)size {
    float oldSize=[size floatValue];
    float newSize=oldSize/1024.0f;
    newSize=newSize/1024.0f;
    return newSize;///[NSString stringWithFormat:@"%f",newSize];
}
///将不M的字符串转化成字节
+(float)transformToBytes:(NSString *)size {
    float totalSize=[size floatValue];
    ///    NSLog(@"文件总大小跟踪：%f",totalSize);
    return totalSize*1024*1024;
}

+(NSString *)getFileSizeString:(NSString *)size {
    if([size floatValue]>=1024*1024) {///大于1M，则转化成M单位的字符串
        return [NSString stringWithFormat:@"%fM",[size floatValue]/1024/1024];
    } else if([size floatValue]>=1024&&[size floatValue]<1024*1024) {///不到1M,但是超过了1KB，则转化成KB单位
        return [NSString stringWithFormat:@"%fK",[size floatValue]/1024];
    } else {///剩下的都是小于1K的，则转化成B单位
        return [NSString stringWithFormat:@"%fB",[size floatValue]];
    }
}

+(float)getFileSizeNumber:(NSString *)size {
    NSInteger indexM=[size rangeOfString:@"M"].location;
    NSInteger indexK=[size rangeOfString:@"K"].location;
    NSInteger indexB=[size rangeOfString:@"B"].location;
    if(indexM<1000) {///是M单位的字符串
        return [[size substringToIndex:indexM] floatValue]*1024*1024;
    } else if(indexK<1000) {///是K单位的字符串
        return [[size substringToIndex:indexK] floatValue]*1024;
    } else if(indexB<1000) {///是B单位的字符串
        return [[size substringToIndex:indexB] floatValue];
    } else {///没有任何单位的数字字符串
        return [size floatValue];
    }
}


#pragma mark - 字符串处理
///转码
+(NSString *)stringFormatTranscoding:(NSData *)strData encoding:(NSStringEncoding)encoding
{
    NSString * strReq = [[NSString alloc] initWithData:strData encoding:encoding];
    return strReq;
}
///格式化字符串，删除回车、换行符等
+(NSString *)stringFormatSymbol:(NSData *)strData{
    NSStringEncoding gbkEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSString * strReq = [[NSString alloc] initWithData:strData encoding:gbkEncoding];///0x80000632
    strReq = [strReq stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
    strReq = [strReq stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    strReq = [strReq stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    strReq = [strReq stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    return strReq;
}
///计算字符串中包含字符个数(全角输入算2个，半角输入算1个)
+(int)stringCount:(NSString *) str{
    int count = 0;
    for (int i = 0; i < str.length; i++) {
        NSRange r = {i,1};
        NSString *strOne = [str substringWithRange:r];
        if ([strOne canBeConvertedToEncoding: NSASCIIStringEncoding]) {
            count++;
///            NSLog(@"输入非中文");
        } else {
            count += 2;
///            NSLog(@"输入中文");
        }
    }
    return count/2;
}
///截取字符串
+(NSString *)cutString:(NSString *)string count:(int)_count{
    int count = 0;
    NSString *outString = @"";
    for (int i = 0; i < string.length; i++) {
        NSRange r = {i,1};
        NSString *strOne = [string substringWithRange:r];
        if ([strOne canBeConvertedToEncoding: NSASCIIStringEncoding]) {
            count++;
        } else {
            count += 2;
        }
        if (count/2 >= _count) {
            outString = [string substringToIndex:i];
            break;
        }
    }
    if (outString.length < 1) {
        outString = string;
    }
    return outString;
}
///HTML符号替换
+(NSString *)stringFomartHTMLSymbol:(NSString *)html
{
    NSString *outString = [html stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
    outString = [outString stringByReplacingOccurrencesOfString:@"&ldquo;" withString:@"“"];
    outString = [outString stringByReplacingOccurrencesOfString:@"&rdquo;" withString:@"”"];
    outString = [outString stringByReplacingOccurrencesOfString:@"&hellip;" withString:@"..."];
    outString = [outString stringByReplacingOccurrencesOfString:@"&mdash;" withString:@"—"];
    outString = [outString stringByReplacingOccurrencesOfString:@"&lsquo;" withString:@"‘"];
    outString = [outString stringByReplacingOccurrencesOfString:@"&rsquo;" withString:@"’"];
    outString = [outString stringByReplacingOccurrencesOfString:@"&lt;" withString:@"《"];
    outString = [outString stringByReplacingOccurrencesOfString:@"&gt;" withString:@"》"];
    
    return outString;
}

///解析url参数类型数据
+ (NSDictionary *)parametersWithSeparator:(NSString *)separator delimiter:(NSString *)delimiter url:(NSString *)str{
    NSArray *parameterPairs =[str componentsSeparatedByString:delimiter];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:[parameterPairs count]];
    for (NSString *currentPair in parameterPairs) {
        NSRange range = [currentPair rangeOfString:separator];
        if(range.location == NSNotFound)
            continue;
        NSString *key = [currentPair substringToIndex:range.location];
        NSString *value =[currentPair substringFromIndex:range.location + 1];
        [parameters setObject:value forKey:key];
    }
    return parameters;
}


#pragma mark - 获取时间
///根据时间格式获取当前时间
+ (NSString *) stringFromTime:(NSString *)strDateFormat {
    NSDate* date = [NSDate date];
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    if ([strDateFormat length] < 1) {
        strDateFormat = @"yyyy-MM-dd HH:mm:ss";
    }
    [formatter setDateFormat:strDateFormat];
    return [formatter stringFromDate:date];
}

#pragma mark - 图像处理
///等比例缩放
+ (UIImage *)scaleImage:(UIImage *)image proportion:(float)scale {
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width/scale, image.size.height/scale));
    CGRect imageRect = CGRectMake(0.0, 0.0, image.size.width/scale, image.size.height/scale);
    [image drawInRect:imageRect];
    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
///颜色转图片
+ (UIImage *)createImageWithColor:(UIColor *) color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
///自定长宽
+ (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize

{
    UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height));
    [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];
    UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return reSizeImage;
    
}
#pragma mark - navbar标题
+(NSString *)getNavBarTitle
{
    NSString *str = [NSString stringWithFormat:@"%@ 星期%@",[self stringFromTime:@"YYYY-MM-dd"],[self formatTimeWeek]];
///    str = [str stringByAppendingString:@"\r八月初八"];
    return str;
}

+(NSString *)formatTimeWeek{
    NSArray *arrWeek = [NSArray arrayWithObjects:@"日",@"一",@"二",@"三",@"四",@"五",@"六", nil];
    int i1 = [[self stringFromTime:@"c"] intValue];
    NSString *strWeek = [arrWeek objectAtIndex:i1 - 1];
    return strWeek;
}
#pragma mark - 加密、解密
+ (NSString *)encryptWithText:(NSString *)sText key:(NSString *)key{
    ///kCCEncrypt 加密
    return [self encrypt:sText encryptOrDecrypt:kCCEncrypt key:key];
}

+ (NSString *)decryptWithText:(NSString *)sText key:(NSString *)key{
    ///kCCDecrypt 解密
    return [self encrypt:sText encryptOrDecrypt:kCCDecrypt key:key];
}

+ (NSString *)encrypt:(NSString *)sText encryptOrDecrypt:(CCOperation)encryptOperation key:(NSString *)key {
    const void *dataIn;
    size_t dataInLength;
    if (encryptOperation == kCCDecrypt) {///传递过来的是decrypt 解码
        NSData* encryptData = [self stringFromHexString:sText];
        dataInLength = [encryptData length];
        dataIn = (const void *)[encryptData bytes];
    } else { ///encrypt
        NSData* encryptData = [sText dataUsingEncoding:NSUTF8StringEncoding];
        dataInLength = [encryptData length];
        dataIn = (const void *)[encryptData bytes];
    }
    
    CCCryptorStatus ccStatus;
    uint8_t *dataOut = NULL;
    size_t dataOutAvailable = 0;
    size_t dataOutMoved = 0;
    
    dataOutAvailable = (dataInLength + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);
    dataOut = malloc( dataOutAvailable * sizeof(uint8_t));
    memset((void *)dataOut, 0x0, dataOutAvailable);
    
    const void *vkey = (const void *) [key UTF8String];
    
    ccStatus = CCCrypt(encryptOperation,///  加密/解密
                       kCCAlgorithmDES,///  加密根据哪个标准（des，3des，aes。。。。）
                       kCCOptionPKCS7Padding|kCCOptionECBMode,///  选项分组密码算法(des:对每块分组加一次密  3DES：对每块分组加三个不同的密)
                       vkey,  ///密钥    加密和解密的密钥必须一致
                       kCCKeySizeDES,///   DES 密钥的大小（kCCKeySizeDES=8）
                       nil, ///  可选的初始矢量
                       dataIn, /// 数据的存储单元
                       dataInLength,/// 数据的大小
                       (void *)dataOut,/// 用于返回数据
                       dataOutAvailable,
                       &dataOutMoved);
    
    NSString *result = nil;
    if (encryptOperation == kCCDecrypt) {///encryptOperation==1  解码
        ///得到解密出来的data数据，改变为utf-8的字符串
        result = [[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)dataOut length:(NSUInteger)dataOutMoved] encoding:NSUTF8StringEncoding];
    } else {///encryptOperation==0
        NSData *data = [NSData dataWithBytes:(const void *)dataOut length:(NSUInteger)dataOutMoved];
        result = [self hexStringFromString:data];
    }
    return result;
}

#pragma mark - 16进制转换
/// 十六进制转换为普通字符串的。
+ (NSData *)stringFromHexString:(NSString *)hexString
{
    char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
    bzero(myBuffer, [hexString length] / 2 + 1);
    for (int i = 0; i < [hexString length] - 1; i += 2) {
        unsigned int anInt;
        NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
        NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
        [scanner scanHexInt:&anInt];
        myBuffer[i / 2] = (char)anInt;
    }
    return [NSData dataWithBytes:myBuffer length:((int)[hexString length] / 2)];
}
///字符串转16进制
+ (NSString *)hexStringFromString:(NSData *)data
{
    Byte *bytes = (Byte *)[data bytes];
    ///下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[data length];i++)
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        if([newHexStr length]==1)
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        else
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    return hexStr;
}

#pragma make - md5加密
///data的MD5加密
+ (NSString *)md5ForData:(NSData*)data
{
    /// const char *str = [string UTF8String];
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(data.bytes, data.length, r);
    return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
}
///NSString的MD5加密
+ (NSString *)md5ForString:(NSString*)str
{
    const char *str1 = [str UTF8String];
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str1, strlen(str1), r);
    return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
}


/////验证联通、移动、电信手机号码
//+(BOOL)isValidatePhone:(NSString *)Phone {
//    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
//    NSPredicate *regextest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
//    return [regextest evaluateWithObject:Phone];
//}
#pragma mark - 正则表达式验证
+ (BOOL) isValidatePhone:(NSString*)Phone
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188,1705
     * 联通：130,131,132,152,155,156,185,186,1709
     * 电信：133,1349,153,180,189,1700
     */
    NSString * MOBILE = @"^1((3//d|5[0-35-9]|8[025-9])//d|70[059])\\d{7}$";//总况
    
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188，1705
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d|705)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186,1709
     17         */
    NSString * CU = @"^1((3[0-2]|5[256]|8[56])\\d|709)\\d{7}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189,1700
     22         */
    NSString * CT = @"^1((33|53|8[09])\\d|349|700)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    
        NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    NSPredicate *regextestphs = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",PHS];
    
    if (([regextestcm evaluateWithObject:Phone] == YES)
        || ([regextestct evaluateWithObject:Phone] == YES)
        || ([regextestcu evaluateWithObject:Phone] == YES)
        || ([regextestphs evaluateWithObject:Phone] == YES)
        || ([regextestmobile evaluateWithObject:Phone] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
    
    
}
////验证电子邮箱
+(BOOL)isValidateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *regextest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [regextest evaluateWithObject:email];
}

@end
